import { setToken, getToken, removeToken } from '../../utils/auth'
import { getUserInfo, getUserDetailById, login } from '@/api/user'
export default {
  namespaced: 'true',
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 设置token
    updateToken (state, token) {
      state.token = token
      setToken(token)
    },
    // 删除缓存
    delToken (state) {
      state.token = ''
      removeToken()
    },
    // 设置用户信息
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo (state) {
      state.userInfo = {}
    }
  },
  actions: {
    async loginAction ({ commit }, payload) {
      const token = await login(payload)
      commit('updateToken', token)
    },
    // 获取用户资料action
    async getUserInfo (context) {
      const result = await getUserInfo()
      const baseInfo = await getUserDetailById(result.userId) // 为了获取头像
      context.commit('setUserInfo', { ...result, ...baseInfo })
      return result
    },
    // 登出
    logout (context) {
      // 清除token
      context.commit('delToken')
      // 清除用户信息
      context.commit('reomveUserInfo')
    }
  }
}
